<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        .box {
            height: 2000px;
        }
        
        .back-top {
            border: 1px solid #ccc;
            height: 30px;
            width: 70px;
            font-size: 12px;
            line-height: 30px;
            text-align: center;
            position: fixed;
            right: 10px;
            bottom: 10px;
            display: none;
        }
    </style>
</head>

<body>
    <div class="box">
        <h3>下滑，点击右下角回到顶部</h3>
    </div>

    <div class="back-top">TOP 点击</div>

    <script>
        let back_top = document.getElementsByClassName('back-top')[0]

        // 滚动条事件
        window.onscroll = () => shake()


        /*
        防抖：鼠标滚动结束后才触发，应该说在滚动事件结束后，一定时间内不再触发才会生效
        setTimeout
        闭包实现变量私有化
        */
        let shake = (function() {
            // 保存定时器变量
            let time = null;

            return function() {
                // 变量为空则清除定时器
                if (time !== null) clearTimeout(time)
                    // 保存定时器
                time = setTimeout(() => {
                    console.log('防抖');
                    // 滚动条高度为0时，隐藏点击按钮
                    if (document.documentElement.scrollTop < 1) return back_top.style.display = 'none'
                        // 滚动条滚动则展示点击按钮
                    back_top.style.display = 'block'
                        // 将滚动条高度重置
                    back_top.onclick = () => {
                        document.documentElement.scrollTop = 0
                    }

                }, 500)
            }
        })();
    </script>
</body>

</html>